#!/usr/bin/python
# -*- coding: UTF-8 -*-

import sys, os

from loguru import logger
import numpy as np
import pyqtgraph as pg
from pyqtgraph.Qt import QtCore

from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QFileDialog
from PyQt5.QtCore import pyqtSignal, QObject

from qt_material import apply_stylesheet

sys.path.append(os.getcwd())
from views.widgets import Ui_image_analysis
from utils import data_bin_parse
import reconDAS as reconDAS

class ImageAnalysisForm(QWidget, Ui_image_analysis.Ui_ImageAnalysis):
    def __init__(self, parent = None):
        super(ImageAnalysisForm, self).__init__(parent)
        self.setupUi(self)

        self.parentMainWindow = None
        self.ReturnHomeButton.clicked.connect(self.returnHome)
        self.NextStepButton.clicked.connect(self.nextStep)

        # tab US/PA重建
        self.pushButton_Recon_SelectFolder.clicked.connect(self.__selectFolder4Recon)
        self.pushButton_US_Recon.clicked.connect(self.__USRecon)
        self.pyqtImageView.setWindowTitle('US Image View')
        self.pyqtImageView.ui.histogram.hide()
        self.pyqtImageView.ui.menuBtn.hide()
        self.pyqtImageView.ui.roiBtn.hide()
        viewBox = self.pyqtImageView.getView()
        viewBox.setBackgroundColor('w')
        self.DASRecon = reconDAS.initialize()
        #pg.setConfigOption('imageAxisOrder', 'row-major')
        #pg.setConfigOption('background', 'w')
        #pg.setConfigOption('foreground', 'k')

        #tab 原始数据查看
        self.binDataParser = None
        self.pushButton_SelectFolder.clicked.connect(self.__selectFolder)
        self.comboBox_bindatalist.currentIndexChanged.connect(self.__readBinData)
        self.lineEdit_channel_number.editingFinished.connect(self.__showRawAcqData)
        self.lineEdit_frame_number.editingFinished.connect(self.__showRawAcqData)

        self.widgetRawData = pg.GraphicsLayoutWidget(show=True, title="原始采集数据")
        self.widgetRawData.setWindowTitle('pyqtgraph example: Plotting')
        pg.setConfigOptions(antialias = True)
        self.plotRawData = self.widgetRawData.addPlot(title="原始采集数据")
        self.gridLayout.addWidget(self.widgetRawData)

        logger.debug("create an instance of ImageAnalysisForm successfully")

    def setMainWindow(self, MainWindow):
        self.parentMainWindow = MainWindow
    
    def returnHome(self):
        if self.parentMainWindow is not None:
            self.parentMainWindow.returnHome()
        else:
            pass
    
    def nextStep(self):
        if self.parentMainWindow is not None:
            self.parentMainWindow.imageAnalysisNextStep()
        else:
            pass
    
    def __selectFolder(self):
        selectedFolder = QFileDialog.getExistingDirectory(None, "选取文件夹", "D:/")
        if selectedFolder == '':
            return
        self.label_FolderPath.setText(selectedFolder)
        self.comboBox_bindatalist.clear()
        for file_name in os.listdir(selectedFolder):
            if os.path.isfile(os.path.join(selectedFolder, file_name)):
                if file_name.endswith('.bin'):
                    self.comboBox_bindatalist.addItem(file_name) 
    
    def __readBinData(self):
        current_select_file = self.comboBox_bindatalist.currentText()
        current_select_file = self.label_FolderPath.text() + "/" + current_select_file
        # TODO :  frame count and channel count 应该来自其他页面的设置
        if not current_select_file.endswith('.bin'):
            return
        self.binDataParser = data_bin_parse.BinDataParser(current_select_file, 7, 64)
        self.binDataParser.parseData()

        logger.debug("parse bin data: {0} successfully", current_select_file)
    
    def __showRawAcqData(self):
        self.selected_frame_number = int(self.lineEdit_frame_number.text())
        self.selected_channel_nmuber = int(self.lineEdit_channel_number.text())
        selected_raw_data = self.binDataParser.getChannelData(self.selected_frame_number, self.selected_channel_nmuber)
        self.plotRawData.clear()
        self.plotRawData.plot(selected_raw_data)

    def __selectFolder4Recon(self):
        selectedFolder = QFileDialog.getExistingDirectory(None, "选取文件夹", "D:/")
        if selectedFolder == '':
            return
        self.label_Recon_FolderPath.setText(selectedFolder)
        self.comboBox_Recon_bindatalist.clear()
        for file_name in os.listdir(selectedFolder):
            if os.path.isfile(os.path.join(selectedFolder, file_name)):
                if file_name.endswith('.bin'):
                    self.comboBox_Recon_bindatalist.addItem(file_name) 

    def __USRecon(self):
        current_select_file = self.comboBox_Recon_bindatalist.currentText()
        current_select_file = self.label_Recon_FolderPath.text() + "/" + current_select_file
        if not current_select_file.endswith('.bin'):
            return
        
        img = self.DASRecon.reconDAS(current_select_file)
        self.pyqtImageView.setImage(np.transpose(np.array(img))) 
        logger.debug("DAS reconstruct bin data: {0} successfully.", current_select_file)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    PAWin = ImageAnalysisForm()
    apply_stylesheet(app, theme = "dark_teal.xml")
    PAWin.show()
    sys.exit(app.exec_())